/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  This product includes software developed by the
 *  Apache Software Foundation (http://www.apache.org/).
 *  The Apache Software Foundation in no way endorses or
 *  promotes this product.
 */
package com.codemagi.taglibs.input;

import com.codemagi.util.UIDGenerator;
import com.codemagi.util.Utils;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

/**
 *  This class implements the &lt;input:token&gt; tag, which presents an 
 *  &lt;input type="hidden" ... /&gt; form element containing a session-specific
 *  token to protect against CSRF attacks. 
 *
 *  @version 1.0
 *  @author August Detlefsen for CodeMagi, Inc.
 */
public class Token extends Input {

    public int doStartTag() throws JspException {
	try {
	    // get what we need from the page
	    ServletRequest req  = pageContext.getRequest();
	    JspWriter out       = pageContext.getOut();
	    HttpSession session = ((HttpServletRequest)req).getSession();

	    //do we already have a token in the session? 
	    String token        = (String)session.getAttribute("token");
	    if ( Utils.isEmpty(token) ) {
		token = UIDGenerator.getUID();
		session.setAttribute("token", token);
	    }

	    // start building up the tag
	    out.println();
	    out.println("<input ");
	    out.println("    type=\"hidden\"");
	    out.println("    name=\"token\"");
	    out.println("    value=\"" + token + "\"");

	    // end the tag
	    out.println("/>");

	} catch (Exception ex) {
	    throw new JspTagException(ex.getMessage());
	}
	return SKIP_BODY;
    }
}
